package com.vcens.dingnotice.exception;

import com.vcens.dingnotice.utils.DataResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;

/**
 * @Author VeChar
 * @Desc    全局异常处理
 * @CreateTime 2018/9/29 11:54 PM
 **/
@ControllerAdvice
@Slf4j
public class GlobalExceptionHandler {
    public static final String DEFAULT_ERROR_VIEW = "error";

    @ExceptionHandler(value = ViewException.class)
    public ModelAndView viewErrorHandler(HttpServletRequest req, Exception e) {
        log.error(e.getMessage(), e);
        ModelAndView mav = new ModelAndView();
        mav.addObject("exception", e);
        mav.addObject("url", req.getRequestURL());
        mav.setViewName(DEFAULT_ERROR_VIEW);
        return mav;
    }

    @ExceptionHandler(value = RestException.class)
    @ResponseBody
    public DataResult restErrorHandler(RestException e) {
        //打印堆栈错误信息
        log.error(e.getMessage(), e);
        //返回数据
        DataResult dataResult = new DataResult();
        dataResult.setMsg("系统异常...");
        dataResult.setStatus(500);
        return dataResult;
    }

    @ExceptionHandler(value = Exception.class)
    public void exceptionHandler(Exception e) {
        log.error(e.getMessage(), e);
    }
}